'use client'

import { useState, useEffect } from 'react'
import { Condition, ConditionType, ComparisonOperator, ActionType, Scene, Action, CreateSceneInput } from '@/types/scene'
import { Modal, Form, Input, Select, message } from 'antd'
import { useRouter } from 'next/navigation'
import React from 'react'

interface Device {
  id: string
  name: string
  type: string
}

interface Sensor {
  id: string
  name: string
  type: 'temperature' | 'humidity' | 'brightness' | 'motion'
  value: number
  unit: string
}

interface AddSceneModalProps {
  open: boolean
  scene?: Scene | null
  onClose: () => void
  onSuccess: () => void
}

interface NewCondition {
  type?: ConditionType
  operator?: ComparisonOperator
  value?: any
  deviceId?: string
  sensorId?: string
}

interface NewAction {
  type?: ActionType
  deviceId?: string
  value?: any
}

export default function AddSceneModal({ open, scene, onClose, onSuccess }: AddSceneModalProps) {
  const [form] = Form.useForm()
  const [loading, setLoading] = useState(false)
  const [groups, setGroups] = useState<Array<{ id: string; name: string }>>([])
  const [name, setName] = useState('')
  const [sensors, setSensors] = useState<Sensor[]>([])
  const [conditions, setConditions] = useState<Condition[]>([])
  const [actions, setActions] = useState<Action[]>([])
  const [showConditionForm, setShowConditionForm] = useState(false)
  const [showActionForm, setShowActionForm] = useState(false)

  const [newCondition, setNewCondition] = useState<NewCondition>({
    type: 'time',
    operator: '='
  })

  const [newAction, setNewAction] = useState<NewAction>({
    type: 'switch'
  })

  // 监听表单值变化
  const [formValid, setFormValid] = useState(false)

  // 添加 devices 状态
  const [devices, setDevices] = useState<Device[]>([])

  // 当 scene 变化时初始化表单数据
  useEffect(() => {
    if (scene) {
      console.log('Scene object:', scene)
      
      // 等待下一个渲染周期再设置表单值
      setTimeout(() => {
        const formData = {
          name: scene.name,
          groupId: scene.groupId
        }
        console.log('Setting form data:', formData)
        form.setFieldsValue(formData)
        
        // 同步更新状态
        setName(scene.name)
        setConditions(scene.conditions || [])
        setActions(scene.actions || [])
      }, 0)
    } else {
      form.resetFields()
      setName('')
      setConditions([])
      setActions([])
    }
  }, [scene, form])

  // 获取分组列表
  const fetchGroups = async () => {
    try {
      const response = await fetch('/api/scene-groups')
      const data = await response.json()
      setGroups(data)
    } catch (error) {
      console.error('获取分组失败:', error)
    }
  }

  // 在弹框打开时获取分组列表
  React.useEffect(() => {
    if (open) {
      fetchGroups()
    }
  }, [open])

  useEffect(() => {
    if (open) {
      // 获取设备列表
      fetch('/api/devices')
        .then(res => res.json())
        .then(data => {
          if (!data.error) {
            setDevices(data)
          }
        })
        .catch(() => {
          message.error('获取设备列表失败')
        })

      // 获取传感器列表
      fetch('/api/sensors')
        .then(res => res.json())
        .then(data => {
          if (!data.error) {
            setSensors(data)
          }
        })
        .catch(() => {
          message.error('获取传感器列表失败')
        })
    }
  }, [open])

  const handleAddCondition = () => {
    if (newCondition.type === 'time') {
      setConditions(prev => [...prev, {
        type: 'time',
        operator: newCondition.operator || '=',
        value: newCondition.value
      } as Condition])
    } else if (newCondition.type === 'device') {
      setConditions(prev => [...prev, {
        type: 'device',
        operator: newCondition.operator || '=',
        value: {
          deviceId: newCondition.deviceId,
          state: newCondition.value as 'on' | 'off'
        }
      } as Condition])
    } else if (newCondition.type === 'temperature' || 
               newCondition.type === 'humidity' || 
               newCondition.type === 'brightness' || 
               newCondition.type === 'motion') {
      setConditions(prev => [...prev, {
        type: newCondition.type,
        operator: newCondition.operator || '=',
        value: newCondition.value,
        sensorId: newCondition.sensorId
      } as Condition])
    }
    setNewCondition({ type: 'time', operator: '=' })
    setShowConditionForm(false)
  }

  const handleAddAction = () => {
    if (newAction.deviceId && newAction.type && newAction.value !== undefined) {
      setActions(prev => [...prev, {
        deviceId: newAction.deviceId!,
        type: newAction.type!,
        value: newAction.value
      } as Action])
      setNewAction({ type: 'switch' })
      setShowActionForm(false)
    }
  }

  const handleSubmit = async (values: any) => {
    setLoading(true)
    try {
      const data = {
        ...values,
        name,
        conditions,
        actions
      }

      if (scene) {
        await fetch(`/api/scenes/${scene.id}`, {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(data),
        })
      } else {
        await fetch('/api/scenes', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(data),
        })
      }
      
      message.success(scene ? '场景更新成功' : '场景创建成功')
      onSuccess()
      onClose()
    } catch (error) {
      console.error('Error:', error)
      message.error(scene ? '场景更新失败' : '场景创建失败')
    } finally {
      setLoading(false)
    }
  }

  const getOperatorOptions = (type: ConditionType | undefined) => {
    if (!type) return []
    
    switch (type) {
      case 'time':
        return [
          { value: '=', label: '等于' }
        ]
      case 'device':
        return [
          { value: '=', label: '等于' }
        ]
      default:
        return [
          { value: '=', label: '等于' },
          { value: '>', label: '大于' },
          { value: '<', label: '小于' },
          { value: '>=', label: '大于等于' },
          { value: '<=', label: '小于等于' }
        ]
    }
  }

  const renderConditionForm = () => {
    if (!showConditionForm) return null

    return (
      <div className="mt-4 p-4 bg-white/5 border border-white/10 rounded-lg">
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-white/80 mb-1">条件类型</label>
            <select
              value={newCondition.type}
              onChange={(e) => setNewCondition({ 
                type: e.target.value as ConditionType,
                operator: '='
              })}
              className="scene-select w-full"
            >
              <option value="time">时间</option>
              <option value="device">设备状态</option>
              <option value="temperature">温度</option>
              <option value="humidity">湿度</option>
              <option value="brightness">亮度</option>
              <option value="motion">运动</option>
            </select>
          </div>

          {newCondition.type === 'time' ? (
            <div>
              <label className="block text-sm font-medium text-white/80 mb-1">时间</label>
              <input
                type="time"
                value={newCondition.value || ''}
                onChange={(e) => setNewCondition({ ...newCondition, value: e.target.value })}
                className="scene-input w-full"
              />
            </div>
          ) : newCondition.type === 'device' ? (
            <>
              <div>
                <label className="block text-sm font-medium text-white/80 mb-1">设备</label>
                <select
                  value={newCondition.value?.deviceId || ''}
                  onChange={(e) => setNewCondition({
                    ...newCondition,
                    value: { ...newCondition.value, deviceId: e.target.value }
                  })}
                  className="scene-select w-full"
                >
                  <option value="">选择设备</option>
                  {devices.map(device => (
                    <option key={device.id} value={device.id}>{device.name}</option>
                  ))}
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-white/80 mb-1">状态</label>
                <select
                  value={newCondition.value?.state || ''}
                  onChange={(e) => setNewCondition({
                    ...newCondition,
                    value: { ...newCondition.value, state: e.target.value }
                  })}
                  className="scene-select w-full"
                >
                  <option value="on">开启</option>
                  <option value="off">关闭</option>
                </select>
              </div>
            </>
          ) : (
            <>
              <div>
                <label className="block text-sm font-medium text-white/80 mb-1">传感器</label>
                <select
                  value={newCondition.sensorId || ''}
                  onChange={(e) => setNewCondition({
                    ...newCondition,
                    sensorId: e.target.value
                  })}
                  className="scene-select w-full"
                >
                  <option value="">选择传感器</option>
                  {sensors
                    .filter(sensor => sensor.type === newCondition.type)
                    .map(sensor => (
                      <option key={sensor.id} value={sensor.id}>{sensor.name}</option>
                    ))
                  }
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-white/80 mb-1">运算符</label>
                <select
                  value={newCondition.operator}
                  onChange={(e) => setNewCondition({
                    ...newCondition,
                    operator: e.target.value as ComparisonOperator
                  })}
                  className="scene-select w-full"
                >
                  {getOperatorOptions(newCondition.type).map(op => (
                    <option key={op.value} value={op.value}>{op.label}</option>
                  ))}
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-white/80 mb-1">
                  阈值 ({sensors.find(s => s.type === newCondition.type)?.unit})
                </label>
                <input
                  type="number"
                  value={newCondition.value || ''}
                  onChange={(e) => setNewCondition({
                    ...newCondition,
                    value: parseFloat(e.target.value)
                  })}
                  className="scene-input w-full"
                />
              </div>
            </>
          )}

          <div className="flex justify-end space-x-2">
            <button
              type="button"
              onClick={() => setShowConditionForm(false)}
              className="px-3 py-1.5 text-sm bg-white/5 text-white/70 rounded-lg
                       hover:bg-white/10 hover:text-white/90 transition-colors"
            >
              取消
            </button>
            <button
              type="button"
              onClick={handleAddCondition}
              className="px-3 py-1.5 text-sm bg-primary-500 text-white rounded-lg
                       hover:bg-primary-600 transition-colors"
            >
              添加
            </button>
          </div>
        </div>
      </div>
    )
  }

  const renderActionForm = () => {
    if (!showActionForm) return null

    const selectedDevice = devices.find(d => d.id === newAction.deviceId)

    const renderActionValueInput = () => {
      if (!selectedDevice) return null

      switch (selectedDevice.type) {
        case 'LIGHT':
          return (
            <>
              <div>
                <label className="block text-sm font-medium text-white/80 mb-1">动作类型</label>
                <select
                  value={newAction.type || 'switch'}
                  onChange={(e) => setNewAction({ 
                    ...newAction, 
                    type: e.target.value as ActionType,
                    value: e.target.value === 'switch' ? 'on' : 
                           e.target.value === 'brightness' ? 100 :
                           e.target.value === 'color' ? '#ffffff' : undefined
                  })}
                  className="scene-select w-full"
                >
                  <option value="switch">开关</option>
                  <option value="brightness">亮度</option>
                  <option value="color">颜色</option>
                </select>
              </div>

              {newAction.type === 'switch' && (
                <div>
                  <label className="block text-sm font-medium text-white/80 mb-1">开关状态</label>
                  <select
                    value={newAction.value || 'on'}
                    onChange={(e) => setNewAction({ ...newAction, value: e.target.value })}
                    className="scene-select w-full"
                  >
                    <option value="on">开启</option>
                    <option value="off">关闭</option>
                  </select>
                </div>
              )}

              {newAction.type === 'brightness' && (
                <div>
                  <label className="block text-sm font-medium text-white/80 mb-1">亮度 (0-100)</label>
                  <input
                    type="range"
                    min="0"
                    max="100"
                    value={newAction.value || 100}
                    onChange={(e) => setNewAction({ ...newAction, value: parseInt(e.target.value) })}
                    className="scene-range w-full"
                  />
                  <div className="text-sm text-white/50 mt-1">{newAction.value}%</div>
                </div>
              )}

              {newAction.type === 'color' && (
                <div>
                  <label className="block text-sm font-medium text-white/80 mb-1">颜色</label>
                  <input
                    type="color"
                    value={newAction.value || '#ffffff'}
                    onChange={(e) => setNewAction({ ...newAction, value: e.target.value })}
                    className="scene-color w-full"
                  />
                </div>
              )}
            </>
          )

        case 'AC':
          return (
            <>
              <div>
                <label className="block text-sm font-medium text-white/80 mb-1">动作类型</label>
                <select
                  value={newAction.type || 'switch'}
                  onChange={(e) => setNewAction({ 
                    ...newAction, 
                    type: e.target.value as ActionType,
                    value: e.target.value === 'switch' ? 'on' : 25
                  })}
                  className="scene-select w-full"
                >
                  <option value="switch">开关</option>
                  <option value="temperature">温度</option>
                </select>
              </div>

              {newAction.type === 'switch' && (
                <div>
                  <label className="block text-sm font-medium text-white/80 mb-1">开关状态</label>
                  <select
                    value={newAction.value || 'on'}
                    onChange={(e) => setNewAction({ ...newAction, value: e.target.value })}
                    className="scene-select w-full"
                  >
                    <option value="on">开启</option>
                    <option value="off">关闭</option>
                  </select>
                </div>
              )}

              {newAction.type === 'temperature' && (
                <div>
                  <label className="block text-sm font-medium text-white/80 mb-1">温度 (16-30°C)</label>
                  <div className="flex items-center space-x-2">
                    <button
                      type="button"
                      onClick={() => setNewAction(prev => ({
                        ...prev,
                        value: Math.max(16, (prev.value as number || 25) - 1)
                      }))}
                      className="px-2 py-1 bg-white/5 rounded"
                    >
                      -
                    </button>
                    <span className="text-lg">{newAction.value || 25}°C</span>
                    <button
                      type="button"
                      onClick={() => setNewAction(prev => ({
                        ...prev,
                        value: Math.min(30, (prev.value as number || 25) + 1)
                      }))}
                      className="px-2 py-1 bg-white/5 rounded"
                    >
                      +
                    </button>
                  </div>
                </div>
              )}
            </>
          )

        case 'CURTAIN':
          return (
            <div>
              <label className="block text-sm font-medium text-white/80 mb-1">开合度 (0-100)</label>
              <input
                type="range"
                min="0"
                max="100"
                value={newAction.value || 0}
                onChange={(e) => setNewAction({ 
                  ...newAction, 
                  type: 'curtain',
                  value: parseInt(e.target.value) 
                })}
                className="scene-range w-full"
              />
              <div className="text-sm text-white/50 mt-1">{newAction.value || 0}%</div>
            </div>
          )

        default:
          return null
      }
    }

    return (
      <div className="mt-4 p-4 bg-white/5 border border-white/10 rounded-lg">
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-white/80 mb-1">设备</label>
            <select
              value={newAction.deviceId || ''}
              onChange={(e) => setNewAction({ 
                deviceId: e.target.value,
                type: 'switch',
                value: 'on'
              })}
              className="scene-select w-full"
            >
              <option value="">选择设备</option>
              {devices.map(device => (
                <option key={device.id} value={device.id}>{device.name}</option>
              ))}
            </select>
          </div>

          {renderActionValueInput()}

          <div className="flex justify-end space-x-2">
            <button
              type="button"
              onClick={() => setShowActionForm(false)}
              className="px-3 py-1.5 text-sm bg-white/5 text-white/70 rounded-lg
                       hover:bg-white/10 hover:text-white/90 transition-colors"
            >
              取消
            </button>
            <button
              type="button"
              onClick={handleAddAction}
              className="px-3 py-1.5 text-sm bg-primary-500 text-white rounded-lg
                       hover:bg-primary-600 transition-colors"
            >
              添加
            </button>
          </div>
        </div>
      </div>
    )
  }

  const renderCondition = (condition: any) => {
    switch (condition.type) {
      case 'device':
        const device = devices.find(d => d.id === condition.deviceId)
        return `设备 ${device?.name || '未知设备'} ${condition.value.state === 'on' ? '开启' : '关闭'}`
      case 'time':
        return `时间 ${condition.value}`
      case 'temperature':
        return `温度 ${condition.operator} ${condition.value}°C`
      case 'humidity':
        return `湿度 ${condition.operator} ${condition.value}%`
      case 'brightness':
        return `亮度 ${condition.operator} ${condition.value}`
      case 'motion':
        return `运动 ${condition.value ? '有' : '无'}`
      default:
        return `${condition.type} ${condition.operator} ${condition.value}`
    }
  }

  const renderAction = (action: Action) => {
    const device = devices.find(d => d.id === action.deviceId)
    switch (action.type) {
      case 'switch':
        return `${device?.name || '未知设备'} ${action.value === 'on' ? '开启' : '关闭'}`
      case 'brightness':
        return `${device?.name || '未知设备'} 亮度设为 ${action.value}%`
      case 'temperature':
        return `${device?.name || '未知设备'} 温度设为 ${action.value}°C`
      case 'color':
        return `${device?.name || '未知设备'} 颜色设为 ${action.value}`
      case 'curtain':
        return `${device?.name || '未知设备'} 开合度设为 ${action.value}%`
      default:
        return `${device?.name || '未知设备'} ${action.type} ${action.value}`
    }
  }

  return (
    <Modal
      title={scene ? "编辑场景" : "创建场景"}
      open={open}
      onCancel={onClose}
      footer={null}
      className="scene-modal"
      styles={{
        content: {
          background: 'rgba(20, 20, 20, 0.95)',
          backdropFilter: 'blur(10px)',
          border: '1px solid rgba(255, 255, 255, 0.15)',
          borderRadius: '16px',
          boxShadow: '0 0 20px rgba(0, 0, 0, 0.5), 0 0 2px rgba(255, 255, 255, 0.1)',
        },
        header: {
          borderBottom: '1px solid rgba(255, 255, 255, 0.1)',
          padding: '20px 24px',
          borderTopLeftRadius: '16px',
          borderTopRightRadius: '16px',
          background: 'rgba(255, 255, 255, 0.03)'
        },
        body: {
          padding: '24px'
        },
        mask: {
          backgroundColor: 'rgba(0, 0, 0, 0.7)',
          backdropFilter: 'blur(4px)'
        }
      }}
      maskClosable={false}
      destroyOnClose
    >
      <Form
        form={form}
        layout="vertical"
        onFinish={handleSubmit}
        onValuesChange={(changedValues, allValues) => {
          if (changedValues.name !== undefined) {
            setName(changedValues.name)
          }
          setFormValid(!!allValues.name)
        }}
        className="mt-4"
        preserve={false}
      >
        <Form.Item
          label={<span className="text-white/80">场景名称</span>}
          name="name"
          rules={[{ required: true, message: '请输入场景名称' }]}
        >
          <Input 
            placeholder="请输入场景名称"
            className="scene-input"
          />
        </Form.Item>

        <Form.Item
          label={<span className="text-white/80">分组</span>}
          name="groupId"
        >
          <Select 
            placeholder="选择分组（可选）"
            className="scene-select"
            options={groups.map(group => ({
              value: group.id,
              label: group.name
            }))}
            allowClear
          />
        </Form.Item>

        <div className="space-y-4 p-4 bg-white/5 rounded-lg border border-white/10">
          <div className="flex justify-between items-center">
            <span className="text-white/80 text-sm font-medium">触发条件</span>
            <button
              type="button"
              onClick={() => setShowConditionForm(true)}
              className="px-3 py-1.5 text-sm bg-primary-500 text-white 
                        rounded-lg hover:bg-primary-600 transition-colors"
            >
              添加条件
            </button>
          </div>
          
          <div className="space-y-2">
            {conditions.map((condition, index) => (
              <div 
                key={index} 
                className="flex justify-between items-center p-3 bg-white/5 
                           rounded-lg border border-white/10"
              >
                <span className="text-white/80 text-sm">
                  {renderCondition(condition)}
                </span>
                <button
                  onClick={() => {
                    setConditions(prev => prev.filter((_, i) => i !== index))
                  }}
                  className="text-white/40 hover:text-white/60 transition-colors"
                >
                  <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                  </svg>
                </button>
              </div>
            ))}
          </div>
          
          {renderConditionForm()}
        </div>

        <div className="space-y-4 mt-4 p-4 bg-white/5 rounded-lg border border-white/10">
          <div className="flex justify-between items-center">
            <span className="text-white/80 text-sm font-medium">执行动作</span>
            <button
              type="button"
              onClick={() => setShowActionForm(true)}
              className="px-3 py-1.5 text-sm bg-primary-500 text-white 
                        rounded-lg hover:bg-primary-600 transition-colors"
            >
              添加动作
            </button>
          </div>
          
          <div className="space-y-2">
            {actions.map((action, index) => (
              <div 
                key={index} 
                className="flex justify-between items-center p-3 bg-white/5 
                           rounded-lg border border-white/10"
              >
                <span className="text-white/80 text-sm">
                  {renderAction(action)}
                </span>
                <button
                  onClick={() => {
                    setActions(prev => prev.filter((_, i) => i !== index))
                  }}
                  className="text-white/40 hover:text-white/60 transition-colors"
                >
                  <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                  </svg>
                </button>
              </div>
            ))}
          </div>
          
          {renderActionForm()}
        </div>

        <div className="flex justify-end space-x-3 mt-6 pt-4 border-t border-white/10">
          <button
            type="button"
            onClick={onClose}
            className="px-4 py-2 bg-white/5 text-white/70 rounded-lg
                     hover:bg-white/10 hover:text-white/90 transition-colors"
          >
            取消
          </button>
          <button
            type="submit"
            className="px-4 py-2 bg-primary-500 text-white rounded-lg
                     hover:bg-primary-600 disabled:opacity-50 
                     disabled:cursor-not-allowed transition-colors"
            disabled={!formValid}
          >
            创建
          </button>
        </div>
      </Form>
    </Modal>
  )
} 